package com.yocard.yxyd.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;
import android.webkit.ValueCallback;
import android.widget.ImageView;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.superluo.textbannerlibrary.TextBannerView;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yocard.yxyd.R;
import com.yocard.yxyd.base.AppContext;
import com.yocard.yxyd.http.model.response.InviteResponse;
import com.yocard.yxyd.others.GifSizeFilter;
import com.yocard.yxyd.others.Glide4Engine;
import com.yocard.yxyd.ui.activity.base.BaseActivity;
import com.yocard.yxyd.ui.contract.InviteFriendsContract;
import com.yocard.yxyd.ui.dialog.InviteFriendsDialog;
import com.yocard.yxyd.ui.dialog.QrCodeDialog;
import com.yocard.yxyd.ui.presenter.InviteFriendsPresenter;
import com.yocard.yxyd.utils.util.ActivityUtils;
import com.yocard.yxyd.utils.util.ToastUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created on 2019/5/28.
 * 邀请好友页面（信贷员分享）
 */
public class InviteFriendsActivity extends BaseActivity<InviteFriendsPresenter> implements InviteFriendsContract.View {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_invite_note)
    TextBannerView tvInviteNote;
    @BindView(R.id.tv_register_num)
    TextView tvRegisterNum;
    @BindView(R.id.tv_cert_num)
    TextView tvCertNum;
    @BindView(R.id.tv_total_num)
    TextView tvTotalNum;
    @BindView(R.id.tv_share_to_friends)
    TextView tvShareToFriends;
    @BindView(R.id.tv_rules)
    TextView tvRules;

    InviteFriendsDialog shareDialog;
    private String inviteUrl;
    private String longUrl;
    private ArrayList<String> notes;
    private boolean resume;

    @Override
    protected int getLayout() {
        return R.layout.act_invite_friends;
    }

    @Override
    protected void initEventAndData() {
        initTitle();
        showLoadingDialog();
        mPresenter.getInviteInfo();
//        tvInviteNote.setText(12, 10, getResources().getColor(R.color.color_ff5306));
//        tvInviteNote.setTextStillTime(2000);//设置停留时长间隔
//        tvInviteNote.setAnimTime(3000);//设置进入和退出的时间间隔
    }

    private void initTitle() {
        ImmersionBar.with(this).statusBarColor(R.color.white).statusBarDarkFont(true).init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @OnClick({R.id.iv_back, R.id.tv_right, R.id.tv_share_to_friends})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_right:
                ActivityUtils.startActivity(InviteRecordsActivity.class);
                break;
            case R.id.tv_share_to_friends:
                if (TextUtils.isEmpty(inviteUrl) || TextUtils.isEmpty(longUrl)) {
                    ToastUtils.showShort("获取分享数据异常！请稍后再试！");
                    return;
                }
                if (shareDialog == null) {
                    shareDialog = new InviteFriendsDialog(this, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {
                            if (InviteFriendsDialog.MOMENTS.equals(value)) {
                                showShare(longUrl, WechatMoments.NAME);
                                return;
                            }
                            if (InviteFriendsDialog.WE_CHAT.equals(value)) {
                                showShare(longUrl, Wechat.NAME);
                                return;
                            }
                            if (InviteFriendsDialog.QR_CODE.equals(value)) {
                                requestPermission();
                            }
                        }
                    });
                }
                shareDialog.show();
                break;
        }
    }

    private void requestPermission() {
        AndPermission.with(AppContext.getContext())
                .runtime()
                .permission(Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)
                .onGranted(permissions -> {
                    showQrCodeDialog();
                })
                .onDenied(permissions -> {
                    ToastUtils.showLong("请授予APP相应权限");
                })
                .start();
    }

    private void showQrCodeDialog() {
        QrCodeDialog qrCodeDialog = new QrCodeDialog(InviteFriendsActivity.this, new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {

            }
        }, inviteUrl);
        qrCodeDialog.show();
    }

    public void showShare(String url, String platform) {
        final OnekeyShare oks = new OnekeyShare();
        //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
        if (platform != null) {
            oks.setPlatform(platform);
        }
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle("优单-信贷经理的展业利器，注册认证即送礼");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("免费抢单啦！我刚在优单上获得免单，邀请您一起获取优质贷款客户");
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform, Platform.ShareParams shareParams) {
                shareParams.setText("免费抢单啦！我刚在优单上获得免单，邀请您一起获取优质贷款客户");
                shareParams.setTitle("优单-信贷经理的展业利器，注册认证即送礼");
                shareParams.setTitleUrl(url);
                shareParams.setUrl(url);
                shareParams.setImageData(BitmapFactory.decodeResource(AppContext.getContext().getResources(), R.mipmap.ico_share));
                shareParams.setShareType(Platform.SHARE_WEBPAGE);
            }
        });
        oks.show(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        tvInviteNote.startViewAnimator();
    }

    @Override
    protected void onStop() {
        super.onStop();
        tvInviteNote.stopViewAnimator();
    }

    @Override
    public void OnFetchInviteInfo(InviteResponse inviteResponse) {
        dismisDialog();
        notes = new ArrayList<String>();
        for (InviteResponse.TrumpetBean trumpetBean : inviteResponse.getTrumpet()) {
            if (trumpetBean != null) {
                String s = String.format(getString(R.string.invite_template_note), trumpetBean.getName(), trumpetBean.getCoin());
                notes.add(s);
            }
        }
        tvInviteNote.setDatas(notes);
        String rule = "";
        for (String s : inviteResponse.getRules()) {
            rule += s + "\n";
        }
        tvRules.setText(rule);
        inviteUrl = inviteResponse.getShort_url();
        longUrl = inviteResponse.getLong_url();
        tvCertNum.setText(String.valueOf(inviteResponse.getShare_approved()));
        tvRegisterNum.setText(String.valueOf(inviteResponse.getShare_register()));
        tvTotalNum.setText(String.valueOf(inviteResponse.getSheet_coin()));
    }

}
